//
//  KaiHuHangViewController.m
//  wangzhe
//
//  Created by 李 佳伟 on 2017/11/23.
//  Copyright © 2017年 李 佳伟. All rights reserved.
//

#import "KaiHuHangViewController.h"
#import "JTCSM.h"
#import "NoticeModel.h"
@interface KaiHuHangViewController ()<UITableViewDelegate,UITableViewDataSource,UISearchBarDelegate,UISearchDisplayDelegate,UITextFieldDelegate,UIAlertViewDelegate>
{
    NSMutableArray *titlearray;
    NSString *page;
    UITableView *_tableview;
    NSString *mykeyword;
    UITextField *textfiled;
    NSString *getBankAddress;
}
@property (nonatomic,strong) UISearchBar *mysearchBar;


@end

@implementation KaiHuHangViewController

- (void)gotBack{
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [df isRemoveTarbar:YES];
    self.navigationController.navigationBar.hidden = NO;
    self.view.backgroundColor =[UIColor whiteColor];
    leftBarButtonItems_rightBarButtonItems *leftbtn = KCUSTOMNAVIGSTION_ALLOC;
    self.navigationItem.leftBarButtonItem = [leftbtn setBarButtonItemsImageName:@"fanhui.png" frame:KLeftBarButtonItemFrame_image target:self SEL:@selector(gotBack)];
    page = @"";
    mykeyword = @"";
    [self layoutTableView];
    [self theRequestWithKeyWord:@""];
    // Do any additional setup after loading the view.
}


- (void)layoutTableView{
    
    _tableview = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, KCONTROLLERWith, KCONTROLLERHeight) style:UITableViewStylePlain];
    _tableview.delegate = self;
    _tableview.dataSource = self;
    [self.view addSubview:_tableview];
    _tableview.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tableview.tableHeaderView = [self createSearchBar];
    [self setUpTableView];
    //    view.backgroundColor = RGBACOLOR(241, 241, 241, 1);
}

- (UISearchBar *)createSearchBar {
    self.mysearchBar = [[UISearchBar alloc]initWithFrame:CGRectMake(0, 5, KCONTROLLERWith, 60)];
    self.mysearchBar.placeholder = @"搜索开户行";
    [self.mysearchBar setImage:[UIImage imageNamed:@"local"] forSearchBarIcon:UISearchBarIconSearch state:UIControlStateNormal];
    [self.mysearchBar setContentMode:UIViewContentModeLeft];
//    [df layerWithView:self.mysearchBar radius:5 width:0 color:nil];
    self.mysearchBar.delegate = self;
    return self.mysearchBar;
}
- (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar

{
    
    mykeyword = searchBar.text;
    [self theRequestWithKeyWord:mykeyword];
    [searchBar resignFirstResponder];
    
    
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self.mysearchBar resignFirstResponder];
    
}
- (void)setUpTableView{
    // 1.下拉刷新(进入刷新状态就会调用self的headerRereshing)
    [_tableview addHeaderWithTarget:self action:@selector(headerRereshing)];
    
    // 上拉加载
    [_tableview addFooterWithTarget:self action:@selector(footerRereshing)];
    
}
- (void)headerRereshing{
    // 2秒后刷新表格UI
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(KRefreshTime * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        //getMarriageSeeking(网络请求)
        [self theRequestWithKeyWord:mykeyword];
    });
}
- (void)footerRereshing{
    // 2秒后刷新表格UI
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(KRefreshTime * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        //getMarriageSeeking(网络请求)
        [self loadMoreDataRequestWithKeyWord:mykeyword];
        
    });
}



- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return titlearray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    NSString *cellid = [NSString stringWithFormat:@"textfield%ld",(long)indexPath.row];
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellid];
    if (cell == nil) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellid ];
    }
    
    if (indexPath == nil || indexPath.row >=titlearray.count) {
        return cell;
    }
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    NoticeModel *model = titlearray[indexPath.row];
//    [cell setvalueWithNoticeModel:model];
    cell.textLabel.text = model.truebank;
    
    return cell;
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 50;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    NoticeModel *model = titlearray[indexPath.row];
    [self.delegate getBankKaiHuHang:model.truebank kaihu_id:model.bankcode];
    [self gotBack];
}

- (void)theRequestWithKeyWord:(NSString *)keyword{
    [titlearray removeAllObjects];
    titlearray = nil;
    titlearray = [NSMutableArray array];
    
    LoadData *request = [[LoadData alloc]init];
    
    [request loadDataPostAsynchronousWithURL:KURLPOSTHeadr(@"User/getTrueBank") withDict:@{@"token":KTokenString,@"bank_name":self.bank_name,@"bank_card":self.bank_card,@"province":self.province,@"city":self.city,@"p":@"",@"keyword":keyword} superView:nil isAddtag:NO Block:^(id result) {
        NSString *isreturn = [NSString stringWithFormat:@"%@",[result objectForKey:@"status"]];
        if ([isreturn isEqualToString:@"1"]) {
            
            NSDictionary *dict = KResultOfKey(@"data");
            NSArray *bannerArr = [dict objectForKey:@"list"];
            page = [dict objectForKey:@"p"];
            for (NSDictionary *bannerdict in bannerArr) {
                NoticeModel *model = [NoticeModel whc_ModelWithJson:bannerdict];
                [titlearray addObject:model];
            }
            
            [_tableview reloadData];
            [_tableview headerEndRefreshing];
        }else{
            [_tableview reloadData];
            [_tableview headerEndRefreshing];
            [df showAlertWithTitle:[result objectForKey:@"msg"] message:nil btn1:@"知道了" btn2:nil btn3:nil delegate:self tag:13];
        }
    }];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (alertView.tag ==KAlertVTag+13) {
        [self gettextfield];
    }
}

- (void)loadMoreDataRequestWithKeyWord:(NSString *)keyword{
    
    LoadData *request = [[LoadData alloc]init];
    [request loadDataPostAsynchronousWithURL:KURLPOSTHeadr(@"User/getTrueBank") withDict:@{@"token":KTokenString,@"bank_name":self.bank_name,@"bank_card":self.bank_card,@"province":self.province,@"city":self.city,@"p":page,@"keyword":keyword} superView:nil isAddtag:NO Block:^(id result) {
        
        NSString *isreturn = [NSString stringWithFormat:@"%@",[result objectForKey:@"status"]];
        if ([isreturn isEqualToString:@"1"]) {
            
            NSDictionary *dict = KResultOfKey(@"data");
            NSArray *bannerArr = [dict objectForKey:@"list"];
            page = [dict objectForKey:@"p"];
            for (NSDictionary *bannerdict in bannerArr) {
                NoticeModel *model = [NoticeModel whc_ModelWithJson:bannerdict];
                [titlearray addObject:model];
            }
            
            [_tableview reloadData];
            [_tableview footerEndRefreshing];
        }
    }];
    
}

- (void)gettextfield{
    
    textfiled = [UITextField initWithframe:CGRectMake(20, 80, KCONTROLLERWith-40, 50) backgrandColor:nil placeholder:@"请输入您银行卡的开户行" textAlignment:NSTextAlignmentLeft font:15 texcolor:RGBACOLOR(89, 89, 89, 1)];
    [_tableview addSubview:textfiled];
    [textfiled addTarget:self  action:@selector(valueChanged:)  forControlEvents:UIControlEventAllEditingEvents];
    [df layerWithView:textfiled radius:4 width:1 color:RGBACOLOR(89, 89, 89, 1)];
    CGFloat surebuttonwidth = 100;
    UIButton *surebutton = [UIButton buttonWithType:UIButtonTypeCustom];
    surebutton.frame = CGRectMake((KCONTROLLERWith-surebuttonwidth)/2, KVIEW_Y(textfiled)+50, surebuttonwidth, 40);
    [surebutton setTitle:@"确定" forState:UIControlStateNormal];
    [surebutton addTarget:self action:@selector(surebutton) forControlEvents:UIControlEventTouchUpInside];
    [surebutton setTitleColor:RGBACOLOR(89, 89, 89, 1) forState:UIControlStateNormal];
    [df layerWithView:surebutton radius:4 width:1 color:RGBACOLOR(89, 89, 89, 1)];
    [_tableview addSubview:surebutton];
    
}
- (void)valueChanged:(UITextField *)textfiled{
    getBankAddress = textfiled.text;
}
- (void)surebutton{
    
    [self.delegate getBankKaiHuHang:getBankAddress== nil ?@"":getBankAddress kaihu_id:@""];
    [self gotBack];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
